/*
 * Copyright (C) hushenglan
 */

#include "mynet.h"

namespace mynet
{

/*
 * 构造函数
 */
CServerSock::CServerSock(int listenPort)
{
    _listenPort = listenPort;

    /* _peerAddr is no use in CServerSock */
    bzero(&_peerAddr, sizeof(_peerAddr));

    /* _localAddr */
    bzero(&_localAddr, sizeof(_localAddr));
    _localAddr.sin_family = AF_INET;
    _localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    _localAddr.sin_port = htons(listenPort);

    _sock = socket(AF_INET, SOCK_STREAM, 0);
}

/*
 * 析构函数
 */
CServerSock::~CServerSock()
{
}

/*
 * 打开监听
 *
 * @return 是否成功
 */
bool CServerSock::listen()
{
    int ret = -1;
    ret = bind(_sock, (struct sockaddr*) &_localAddr, sizeof(_localAddr));
    if (ret != 0)
    {
        /* error */
        return false;
    }

    ret = listen(_sock, MS_LISTEN_BACKLOG);
    if (ret != 0)
    {
        /* error */
        return false;
    }

    return true;
}

/*
 * accept一个新的连接
 *
 * @return 一个Socket
 */
CSock* CServerSock::accept()
{
    int connfd = -1;
    struct sockaddr_in clientAddr;
    int clientLen = -1;

    connfd = accept(_sock, (struct sockaddr*) &clientAddr, (socklen_t*) &clientLen);
    if (connfd == -1)
    {
        /* error */
        return NULL;
    }

    CSock *ClientSock = new CTcpSock(connfd);

    return ClientSock;
}

}
